package com.fridge.fridgeList;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.fridge.data.DBHelper;
import com.fridge.data.FridgeItem;
import com.fridge.data.ShoppingItem;
import com.fridge.shopping.AddShoppingItemActivity;
import com.id2216.fridge.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class AddFridgeItemActivity extends Activity {

	
	EditText editNameText;
	Button pickDate;
	TextView dateLabel;
	Button confirmAdd;
	ImageButton selectImage;
	ImageView userImage;
	Date date;
	
	String selectedImagePath;
	 
	private DBHelper db;

	private static final int SELECT_PHOTO = 101;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_fridge);
		
		
		editNameText = (EditText) this.findViewById(R.id.fridgeNameTextBox);
		pickDate = (Button) this.findViewById(R.id.datePickerButton);
		confirmAdd = (Button) this.findViewById(R.id.addFridgeOk);
		selectImage = (ImageButton) this.findViewById(R.id.takePicture);
		dateLabel = (TextView) this.findViewById(R.id.dateLabel);
		userImage = (ImageView) this.findViewById(R.id.fridgeItemImage);
		
		date = new Date();
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
	    String format = dateFormat.format(date);
	      	
	    dateLabel.setText(format);

		
		selectImage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);			
				photoPickerIntent.setType("image/*");				
				startActivityForResult(photoPickerIntent, SELECT_PHOTO); 
			}
		});
		
		confirmAdd.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				
            	if(editNameText.getText().length() > 0 && date != null)
            	{
            		
                    db = new DBHelper(getApplicationContext());                    
                    String name = editNameText.getText().toString();                    
                    FridgeItem item = new FridgeItem();
                    item.setName(name);                    
                    item.setExpire(date);
                    if( selectedImagePath != null)
                    	item.setPic(selectedImagePath);
                    
                    db.addFridgeItem(item);                    
                    db.closeDB();
                    
                    AddFridgeItemActivity.this.finish();

            	}
            	else
            	{
	                if( date == null)
	                {
		                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddFridgeItemActivity.this);
		                alertDialog.setMessage("Expire date is empty");
		                alertDialog.setMessage("Please fill item expire date");
		                alertDialog.setCancelable(false);
		                alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                           public void onClick(DialogInterface dialog, int id) {
		                                //do things
		                           }
		                       });
		                AlertDialog alert = alertDialog.create();
		                alert.show();
	                }
	                else
	                {
		                AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddFridgeItemActivity.this);
		                alertDialog.setMessage("Name is empty");
		                alertDialog.setMessage("Please fill item name");
		                alertDialog.setCancelable(false);
		                alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                           public void onClick(DialogInterface dialog, int id) {
		                                //do things
		                           }
		                       });
		                AlertDialog alert = alertDialog.create();
		                alert.show();

	                }
            	}
				
			}
		});
		
		pickDate.setOnClickListener(new View.OnClickListener() {
            
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDateDialog();
			}

            });
	
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
	 
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

	    
	    switch(requestCode) { 
	    case SELECT_PHOTO:
	        if(resultCode == RESULT_OK){  
	            Uri selectedImage = imageReturnedIntent.getData();
	            InputStream imageStream = null;
				try {
					imageStream = getContentResolver().openInputStream(selectedImage);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if( imageStream != null)
				{
					selectedImagePath = getRealPathFromURI(selectedImage);
		            Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);		
		            userImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
		            userImage.setPadding(8, 8, 8, 8);
		            userImage.setImageBitmap(yourSelectedImage);		            
				}
	        }
	    }
	}
	
	   private String getRealPathFromURI(Uri contentURI) {
		    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
		    if (cursor == null) { // Source is Dropbox or other similar local file path
		        return contentURI.getPath();
		    } else { 
		        cursor.moveToFirst(); 
		        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
		        return cursor.getString(idx); 
		    }
		}
	void showDateDialog()
	{
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        DateSetListener dateListener = new DateSetListener();
        DatePickerDialog datePicker = new DatePickerDialog(this, dateListener, year, month, day);                
        datePicker.show();
	}
	
    class DateSetListener implements DatePickerDialog.OnDateSetListener {

    	DateSetListener()
    	{
    	
    	}
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
        	
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, monthOfYear, dayOfMonth);
            date = calendar.getTime();            
            
  	      	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
  	      	String format = dateFormat.format(date);
  	      	
  	      	dateLabel.setText(format);

        }
    }
}
